<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';


import Vditor from 'vditor';
import TablePersonCard from '@/components/Person/TablePersonCard.vue';
import md from '@/utils/markdown';
import router from '@/router';
import 'vditor/dist/index.css';
import 'katex/dist/katex.css';
import {
  getCurrentTrain,
  getGroupDetail, getGroupTrainingIndex,
  getMemberIndexInfo, getMemberSelfTrainingTodo, groupMemberSignIn, ICurrentTrain,
  IGroupDetail, IGroupTrainingIndexItem,
  IMemberIndexInfo, IMemberSignIn, IMemberTrainingTodo, modifyMemberRemark,
  updateGroupAnnouncement
} from '@/api/group';
import { STATIC_URL } from '@/config/config';
import { message } from 'ant-design-vue';


const changeMarkdown = (content: string) => {
  content = md.render(content);
  return content;
};

const showContentEditor = ref(false);
const vditor = ref<Vditor | null>(null);
const isLoading = ref<boolean>(true);

const editContent = () => {
  console.log('Edit button clicked');
  handleShowContentEditor();

};

const handleShowContentEditor = () => {
  showContentEditor.value = true;
  setTimeout(() => {
    vditor.value = new Vditor('announcement-editor', {
      after: () => {
        vditor.value!.setValue(groupDetailInfo.value.announcement);
      },
      height: 'auto',
      placeholder: '请输入markdown格式的内容',
      mode: 'sv',
    });
  });
};

const handAnnouncementUpdate = async () => {
  const res = await updateGroupAnnouncement(groupId.value, {
    'announcement': groupDetailInfo.value.announcement,
  });
  groupDetailInfo.value.announcement = res.announcement;
};

const handleContentOK = async () => {
  groupDetailInfo.value.announcement = vditor.value!.getValue();
  showContentEditor.value = false;
  await handAnnouncementUpdate();
};

const memberIndexInfo = ref<IMemberIndexInfo>({});
const groupTrainIndex = ref<IGroupTrainingIndexItem[]>();
const myCurrentTraining = ref<ICurrentTrain[]>([]);
const myTrainingTodo = ref<IMemberTrainingTodo[]>([]);


const parseTodoList = (data: any[]): IMemberTrainingTodo[] => {
  return data.map(item => ({
    ...item,
    recurrence_days: JSON.parse(item.recurrence_days),
  }));
};

const cache = new Map<number, Promise<any>>();


const fetchAllData = async (id: number) => {
  if (cache.has(id)) {
    console.log('使用缓存加载');
    return cache.get(id)!;
  }


  const [groupTrainIndexRes, myCurrentTrainingRes, groupDetailInfoRes, memberIndexInfoRes, myTrainingTodoRes] = await Promise.all([
    getGroupTrainingIndex(id),
    getCurrentTrain(id),
    getGroupDetail(id),
    getMemberIndexInfo(id),
    getMemberSelfTrainingTodo(id)
  ]);

  const parsedMyTrainingTodo = parseTodoList(myTrainingTodoRes.list);

  const result = {
    groupTrainIndex: groupTrainIndexRes.list,
    myCurrentTraining: myCurrentTrainingRes.list,
    groupDetailInfo: groupDetailInfoRes,
    memberIndexInfo: memberIndexInfoRes,
    myTrainingTodo: parsedMyTrainingTodo
  };

  cache.set(id, Promise.resolve(result));

  return result;
};

const fetchGroupBaseInfo = async (id: number) => {
  const res = await fetchAllData(groupId.value);
  groupTrainIndex.value = res.groupTrainIndex;
  myCurrentTraining.value = res.myCurrentTraining;
  groupDetailInfo.value = res.groupDetailInfo;
  memberIndexInfo.value = res.memberIndexInfo;
  myTrainingTodo.value = res.myTrainingTodo;

  isLoading.value = false;
};

const groupId = ref<number>(0);
const groupDetailInfo = ref<IGroupDetail>({});
onMounted(async () => {
  groupId.value = Number(router.currentRoute.value.params.groupId);
  await fetchGroupBaseInfo(groupId.value);
});

const memberSignIn = async (trainId: number, recordType: number, index: number) => {
  const data = {
    member: memberIndexInfo.value.id,
    training: trainId,
    record_type: recordType,
  };
  const res = await groupMemberSignIn(groupId.value, data);
  if (res.record_type !== 3) {
    message.success('签到成功');
  }
  myCurrentTraining.value[index].status = res.record_type;
};

const modifySelfNameModal = ref<boolean>(false);
const modifySelfRemark = ref<string>('');
const modifySelfRemarkConfirmLoading = ref<boolean>(false);
const handleModifySelfName = async () => {
  modifySelfRemarkConfirmLoading.value = true;
  const res = await modifyMemberRemark(groupId.value, { name: modifySelfRemark.value });
  memberIndexInfo.value.name = res.name;
  modifySelfRemarkConfirmLoading.value = false;
  modifySelfNameModal.value = false;
  message.success('修改备注成功');
};

watch(modifySelfNameModal, (newValue) => {
  if (newValue) {
    modifySelfRemark.value = memberIndexInfo.value.name;
  }
});

</script>

<template>

  <a-layout v-if="!isLoading">
    <a-layout-content style="width: 75%">
      <div style="background: #F0F2F5; margin-right: 16px!important;">
        <a-card :bordered="false" class="shadow">
          <template #title>
            <div class="card-title" style="font-size: 24px; font-weight: bolder ">团队公告</div>
          </template>
          <template #extra v-if="memberIndexInfo.isAdmin"><a class="link-primary text-decoration-none" type="button"
                                                             @click="editContent">编辑</a>
          </template>
          <div v-html="changeMarkdown(groupDetailInfo.announcement)"></div>
          <a-modal
              v-model:visible="showContentEditor"
              width="80vw"
              title="题目内容"
              :body-style="{ height: '80vh', overflow: 'auto' }"
              centered
              ok-text="确认"
              cancel-text="取消"
              @ok="handleContentOK">
            <div id="announcement-editor"></div>
          </a-modal>
        </a-card>


        <a-card class="shadow" style="margin-top:16px;">
          <template #title>
            <div class="card-title" style="font-size: 24px; font-weight: bolder">今日训练名单</div>
            <a-list :grid="{ gutter: 16 , column: 3 }" :data-source="groupTrainIndex">
              <template #renderItem="{ item , index }">
                <a-list-item>
                  <a-list-item-meta :description="item.name">
                    <template #title>
                      <a href="#" type="button" class="link-primary"
                         style="text-decoration-line: none;">{{ item.member.name }}</a>
                    </template>
                    <template #avatar>
                      <a-avatar :src="STATIC_URL + item.member.avatar">
                        {{ item.member.name }}
                      </a-avatar>
                    </template>
                  </a-list-item-meta>
                  <div style="right: 0;">
                    签到状态：
                    <a-tag :color="['#f81e1e' , '#87d068' , '#108ee9' , '#f3c23e'][item.status]">
                      {{ ['缺勤', '已签到', '请假', '未操作'][item.status] }}
                    </a-tag>
                  </div>
                </a-list-item>
              </template>
            </a-list>

          </template>
        </a-card>

        <a-card class="shadow" style="margin-top:16px;">
          <template #title>
            <div class="card-title" style="font-size: 24px; font-weight: bolder"> 讨论区</div>
          </template>
        </a-card>
      </div>
    </a-layout-content>
    <a-layout-sider style="background-color: #F0F2F5;">
      <a-card class="shadow ">
        <div style="font-size: 16px;font-weight: bold;" class="mb-2"> 团队信息</div>
        <div>所有人：
          <TablePersonCard :person="groupDetailInfo.baseInfo.creator"/>
        </div>
        <div class="mt-2">公开度：
          <template v-if="groupDetailInfo.baseInfo.teamType===1"><span>公开</span></template>
          <template v-else><span>私有</span></template>
        </div>
        <div class="mt-2">团队人数：{{ groupDetailInfo.baseInfo.memberCount }}</div>
        <div class="mt-2">创建时间：{{ groupDetailInfo.baseInfo.createTime }}</div>
        <div class="mt-2">团队编号：{{ groupDetailInfo.id }}</div>
      </a-card>

      <a-card :bordered="false" class="shadow" style="margin-top:16px;">
        <div style="font-size: 16px;font-weight: bold;" class="mb-2"> 个人信息</div>

        <div class="mb-2"> 备 注：{{ memberIndexInfo.name }} <a type="link" href="#" @click="modifySelfNameModal = true">修改</a>
        </div>
        <div class="mb-2"> 团队积分：{{ memberIndexInfo.rating }}</div>
        <div> 团队排名：{{ memberIndexInfo.rank }}</div>

        <a-modal
            v-model:visible="modifySelfNameModal"
            :confirm-loading="modifySelfRemarkConfirmLoading"
            title="修改备注"
            centered
            ok-text="确认"
            cancel-text="取消"
            @ok="handleModifySelfName">
          <a-input v-model:value="modifySelfRemark" placeholder="请输入备注"/>
        </a-modal>

      </a-card>
      <a-card :bordered="true" class="shadow" style="margin-top:16px;">
        <div style="font-size: 16px;font-weight: bold;" class="mb-2"> 我的训练</div>
        <a-list item-layout="vertical" :data-source="myCurrentTraining">
          <template #renderItem="{ item , index }">
            <a-list-item>
              <a-list-item-meta
                  :description="'结束时间:' + new Date(item.end_time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })">
                <template #title>
                  <div class="text-truncate">{{ item.name }}</div>
                </template>
              </a-list-item-meta>
              <div style="text-align: center;">
                <template v-if="item.status === 3">
                  <a-button type="primary" :disabled="false" @click="memberSignIn(item.id, 1 , index)">
                    签到
                  </a-button>
                </template>
                <template v-else-if="item.status === 1">
                  <a-button type="primary" :disabled="true">
                    已签到
                  </a-button>
                </template>
                <template v-else-if="item.status === 2">
                  <a-button type="primary" :disabled="true">
                    已请假
                  </a-button>
                </template>
                <template v-else-if="item.status === 0">
                  <a-button type="primary" :disabled="false" danger>
                    缺勤
                  </a-button>
                </template>
              </div>
            </a-list-item>
          </template>
        </a-list>
      </a-card>

      <a-card :bordered="false" class="shadow" style="margin-top:16px">
        <div style="font-size: 16px;font-weight: bold;" class="mb-2"> 近日事项</div>
        <a-list item-layout="horizontal" :data-source="myTrainingTodo">
          <template #renderItem="{ item }">
            <a-list-item>
              <a-list-item-meta :title="item.name">

                <template #description>
                  <div>{{
                      '时间：' + new Date(item.start_time).toLocaleTimeString([], {
                        hour: '2-digit',
                        minute: '2-digit'
                      }) + '-' + new Date(item.end_time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
                    }}
                  </div>
                  <template v-if="item.training_type===0">
                    <div> 周期：{{ item.recurrence_days.toString() }}</div>
                  </template>
                  <template v-else>
                    <div>日期：{{
                        new Date(item.start_time).toLocaleDateString([], {
                          year: 'numeric',
                          month: 'numeric',
                          day: 'numeric'
                        })
                      }}
                    </div>
                  </template>
                </template>
              </a-list-item-meta>
              <template #extra>
                <a type="link" href="#">详细</a>
              </template>
            </a-list-item>
          </template>
          <template #loadMore :style="{textAlign: 'right'}">
            <a type="link" href="#">更多</a>
          </template>
        </a-list>
      </a-card>
    </a-layout-sider>
  </a-layout>
</template>

<style lang="less">

/* 在这里添加KaTeX的CSS样式 */
</style>
